package com.lfsenior.mq;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by dlupan on 2018/10/10
 * 测试发布订阅模式
 */
public class TestPublisher {
    public static final String CHANNEL = "testChannel";
    public static final String HOST = "127.0.0.1";
    public static final int PORT = 6379;

    private final static JedisPoolConfig POOL_CONFIG = new JedisPoolConfig();
    private final static JedisPool JEDIS_POOL = new JedisPool(POOL_CONFIG, HOST, PORT, 0);

    public static void main(String[] args){
        final Jedis publisherJedis = JEDIS_POOL.getResource();
        /*
        * 定义多个订阅端
        * */
        for(int i=0;i<3;i++){
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Jedis subscriberJedis = JEDIS_POOL.getResource();
                        Subscriber subscriber = new Subscriber();
                        System.out.println("Subscribing to mychannel,this thread will be block");
                        subscriberJedis.subscribe(subscriber, CHANNEL);
                        System.out.println("subscription ended");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        new Publisher(publisherJedis, CHANNEL).startPublish();
        publisherJedis.close();

//        subscriber.unsubscribe();
//        subscriberJedis.close();

    }
}
